import re
import base64
from rest_framework import serializers
from apps.czb.models import Orders as CzbOrder
from django.contrib.auth import get_user_model
from rest_framework_jwt.settings import api_settings
from finance_c2c.settings import REGEX_MOBILE
from apps.user_operation.utils import jwt_payload_handler
from .client import TlAuth
from core.tools.CustomFieldsModelSerializer import DynamicFieldsModelSerializer
from apps.coffee.models import CoffeeOrder
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
UserModel = get_user_model()

orderModel = (("czb", "车主邦加油"),)


# 申请支付链接（H5支付）
class PaySerializers(serializers.Serializer):
    supply_id = serializers.IntegerField(write_only=True, label="提交订单时返回的订单id",
                                         error_messages={"blank": "订单supply_id不能为空"}, help_text="系统内部订单id")
    redirect_url = serializers.CharField(write_only=True, label="重定向结果页面的url", required=True,
                                         error_messages={"blank": "重定向结果页面不能为空"}, help_text="前端重定向链接")
    pay_order_model = serializers.ChoiceField(write_only=True, required=False, allow_null=True, allow_blank=True,
                                              choices=orderModel, label="支付订单类型")
    channel = serializers.CharField(write_only=True, label="渠道", required=False, allow_null=True, allow_blank=True)

    def validate_supply_id(self, attrs):
        if self.context["request"].POST.get("pay_order_model") == "czb":
            czb_order_instance = CzbOrder.objects.get(id=attrs)
            if czb_order_instance.result == 1:
                serializers.ValidationError("已经支付过了")
            if czb_order_instance.result == 2:
                serializers.ValidationError("此订单已退款，请重新下单")
            if czb_order_instance.result == 3:
                serializers.ValidationError("此订单有误，请重新下单")
            if czb_order_instance.result == 101:
                serializers.ValidationError("此订单已取消，请重新下单")
        return attrs

    def update(self, instance, validated_data):
        pass

    def create(self, validated_data):
        pass


# 登录
class MyLoginSerializer(serializers.Serializer):
    merchantCode = serializers.CharField(write_only=True, label="服务商编码", help_text="服务商编码")
    version = serializers.CharField(write_only=True, label="版本", help_text="版本", default="1.0")
    appId = serializers.CharField(write_only=True, label="APPID", help_text="APPID")
    custCode = serializers.CharField(write_only=True, label="平台用户编码", help_text="平台用户编码")
    custPhone = serializers.CharField(write_only=True, label="用户手机号", help_text="用户手机号")
    bankCode = serializers.CharField(write_only=True, label="银行编码", help_text="银行编码")
    bankEntryType = serializers.CharField(write_only=True, label="银行入口类型", help_text="银行入口类型")
    signMsg = serializers.CharField(write_only=True, label="signMsg", help_text="signMsg")
    senceCode = serializers.CharField(write_only=True, label="senceCode", help_text="senceCode")
    bankEntryCode = serializers.CharField(write_only=True, label="bankEntryCode", help_text="bankEntryCode")
    channel = serializers.CharField(write_only=True, label="channel", help_text="channel")

    class Meta:
        fields = "__all__"

    def validate_signMsg(self, signMsg):
        tl_auth = TlAuth()
        custPhone = self.initial_data["custPhone"]
        channel = self.initial_data.get("channel")
        print(channel, "cid")
        cipher_text = base64.urlsafe_b64decode(custPhone)
        m = base64.b64decode(cipher_text)
        mobile = tl_auth.decrypt_with_rsa(m)
        self.custPhone = mobile
        parameters = {
            "merchantCode": self.initial_data.get("merchantCode"),
            "version": self.initial_data.get("version"),
            "appId": self.initial_data.get("appId"),
            "custCode": self.initial_data.get("custCode"),
            "custPhone": mobile,
            "bankCode": self.initial_data.get("bankCode"),
            "bankEntryCode": self.initial_data.get("bankEntryCode"),
            "bankEntryType": self.initial_data.get("bankEntryType"),
            "senceCode": self.initial_data.get("senceCode"),
        }
        base_sorted = ["merchantCode", "version", "appId", "custCode", "custPhone", "bankCode", "bankEntryCode",
                       "bankEntryType", "senceCode"]
        source = tl_auth.get_source_add_key(parameters, base_sorted)
        verify_result = tl_auth.Oauth_verify_with_public_key(signMsg, source, channel)
        if not verify_result:
            raise serializers.ValidationError("验签不通过")
        return signMsg

    def create(self, validated_data):
        mobile = self.custPhone
        try:
            user = UserModel.objects.get(mobile=mobile)
        except UserModel.DoesNotExist as e:
            from apps.user_operation.models import LevelDesc
            user = UserModel.objects.create(
                mobile=mobile,
                level=LevelDesc.objects.get(level=1),
                username=mobile,
            )
        if validated_data.get("openid_e"):
            user.wx_user = validated_data["openid_e"]
            user.save()
        return user

    def update(self, instance, validated_data):
        pass

    def validate(self, attrs):
        user = self.create(attrs)
        payload = jwt_payload_handler(self, user)
        token = jwt_encode_handler(payload)
        setattr(self, 'object', {"user": user, "token": token})
        return {
            'token': token,
            'user': user
        }


class CoffeeOrderSerializer(DynamicFieldsModelSerializer):
    user = serializers.HiddenField(default=serializers.CurrentUserDefault())

    def update(self, instance, validated_data):
        instance.pay_type = 97
        instance.save()
        return instance

    class Meta:
        model = CoffeeOrder
        fields = ("user",)